package com.ely.coupon.activity.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ely.coupon.activity.service.GenerateCouponCodeService;
import com.ely.coupon.common.redis.dao.RedisDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 大文件
 * 数据导入导出
 */
@Service
@Slf4j
public class GenerateCouponCodeServiceImpl implements GenerateCouponCodeService {
    public static final String CODE_COUPON_KEY_SUFFIX = "code:coupon:id:";
    @Resource
    private RedisDao redisDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ListOperations<String, Object> listOperations;
    // 根据业务规则异步生成优惠券码
    // 将优惠券码保存Redis中

    /**
     * code:coupon:id:
     */
    @Async
    @Override
    public void asyncGenerateCouponCode(int couponQuantity, Long couponActivityId, Date endDate) {
        //  生成优惠券码
        Set<String> codeList = Stream.generate(() -> RandomUtil.randomNumbers(4)).limit(couponQuantity).map(num -> StrUtil.format("{}{}", DateUtil.format(new Date(), "yyyyMMddHHmmss"), num)).collect(Collectors.toSet());
        listOperations.rightPushAll(CODE_COUPON_KEY_SUFFIX + couponActivityId, codeList.toArray());
        redisTemplate.expireAt(CODE_COUPON_KEY_SUFFIX + couponActivityId, endDate);
    }
}
